<template>
  <div>
    <el-form :model="froPermissionSearch" inline ref="searchFormRef">
      <el-form-item label="菜单名称" prop="permissionName">
        <el-input v-model="froPermissionSearch.permissionName"></el-input
        >
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
            v-model="froPermissionSearch.status"
            placeholder="请选择状态"
            style="width: 240px"
        >
          <el-option label="正常" :value="0"/>
          <el-option label="禁用" :value="1"/>
          <el-option label="全部" :value="-1"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search">查询</el-button>
      </el-form-item>
      <el-form-item
      >
        <el-button :icon="Refresh" type="primary" @click="resetSearch(searchFormRef)"
        >重置
        </el-button
        >
      </el-form-item
      >
    </el-form>
    <el-button :icon="Plus" size="small" type="primary" @click="addfroPermission(0)"
    >新增
    </el-button
    >
    <el-table :data="froPermissionList" style="width: 100%" row-key="permissionId">
      <el-table-column prop="permissionId" label="编号" width="150px"/>
      <el-table-column prop="permissionName" label="名称"/>
      <el-table-column label="图标">
        <template #default="scope">
          <component :is="scope.row.icon" class="icon-size"></component
          >
        </template>
      </el-table-column>
      <el-table-column prop="permissionKey" label="标识"/>
      <el-table-column prop="component" label="组件"/>
      <el-table-column prop="path" label="全路由"/>
      <el-table-column prop="url" label="路径"/>
      <el-table-column prop="createTime" label="创建时间" :formatter="dateFormat"/>
      <el-table-column label="操作" width="200px">
        <template #default="scope">
          <div class="flex-hcenter">
            <div @click="modifyfroPermission(scope.row)">
              <el-icon>
                <EditPen/>
              </el-icon>
              <el-text>修改</el-text>
            </div>
            <el-divider direction="vertical"/>
            <div @click="addfroPermission(scope.row.permissionId)">
              <el-icon>
                <Plus/>
              </el-icon>
              <el-text>新增</el-text>
            </div>
            <el-divider direction="vertical"/>
            <div @click="deletefroPermission(scope.row.permissionId)">
              <el-icon>
                <Delete/>
              </el-icon>
              <el-text>删除</el-text>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        v-model="dialogFormVisible"
        :title="dialogIsAdd ? '新增' : '修改'"
        width="600"
        draggable
        @close="resetForm(ruleFormRef)"
    >
      <el-form :model="froPermission" label-width="100" :rules="rules" ref="ruleFormRef">
        <el-form-item label="图标" prop="icon">
          <el-input v-model="froPermission.icon"></el-input
          >
        </el-form-item>
        <el-form-item label="权限标识" prop="permissionKey">
          <el-input v-model="froPermission.permissionKey" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="权限名称" prop="permissionName">
          <el-input v-model="froPermission.permissionName"></el-input>
        </el-form-item>
        <el-form-item label="层级" prop="parentId">
          <el-tree-select
              style="max-width: 500px"
              check-strictly
              node-key="permissionId"
              v-model="froPermission.parentId"
              :data="froPermissionFlode"
              :props="defaultProps"
              show-checkbox
          />
        </el-form-item>
        <el-form-item label="权限类型" prop="permissionType">
          <el-radio-group v-model="froPermission.permissionType">
            <el-radio :value="0">目录</el-radio>
            <el-radio :value="1">页面</el-radio>
            <el-radio :value="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="组件位置" prop="component" @mouseover="(e) => (buttonRef = e.currentTarget)"
        >
          <el-input v-model="froPermission.component"></el-input
          >
        </el-form-item>
        <el-tooltip content="组件路由全路径，以/layout开始，多个单词以-分隔" placement="top">
          <el-form-item label="访问路由" prop="path"
          >
            <el-input v-model="froPermission.path"></el-input
            >
          </el-form-item>
        </el-tooltip>
        <el-tooltip content="组件路由部分路径，去掉/layout,用于动态添加路由" placement="top">
          <el-form-item label="路径" prop="url"
          >
            <el-input v-model="froPermission.url"></el-input
            >
          </el-form-item>
        </el-tooltip>
        <el-form-item label="状态" prop="status"
        >
          <el-input v-model="froPermission.status"></el-input
          >
        </el-form-item>
        <el-form-item label="是否显示" prop="isShow">
          <el-radio-group v-model="froPermission.isShow">
            <el-radio :value="0">显示</el-radio>
            <el-radio :value="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否可关闭" prop="isClosable">
          <el-radio-group v-model="froPermission.isClosable">
            <el-radio :value="0">不可关闭</el-radio>
            <el-radio :value="1">可以关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="savefroPermission(ruleFormRef)">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-tooltip
        ref="tooltipRef"
        :visible="visible"
        :popper-options="{
      modifiers: [
        {
          name: 'computeStyles',
          options: {
            adaptive: false,
            enabled: false,
          },
        },
      ],
    }"
        :virtual-ref="buttonRef"
        virtual-triggering
        popper-class="singleton-tooltip"
    >
      <template #content>
        <span> 组件从home目录下开始，且不用/起始 </span>
      </template>
    </el-tooltip>
  </div>
</template>
<script lang="ts" setup>
import {reactive, ref, onMounted, watch} from "vue";
import {Plus, Search, Refresh, EditPen, Delete} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import moment from 'moment';
import type {FormInstance, FormRules} from "element-plus";
import type {froPermission, froPermissionTreeVO} from "@/api/front/permission/type";
import {
  reqGetFroPermissionTreeList,
  reqAddFroPermission,
  reqModifyFroPermission,
  reqGetFroPermissionFolder,
  reqDeleteFroPermission,
} from "@/api/frotem/permission/index";

let froPermissionList = ref<froPermissionTreeVO[]>([]);
let froPermissionFlode = ref<froPermissionTreeVO[]>([
  {
    permissionId: 0,
    permissionKey: "",
    permissionName: "一级目录",
    parentId: 0,
    createTime: "",
    createBy: "",
    path: "",
    component: "",
    permissionType: 0,
    status: 0,
    remark: "",
    icon: "",
    url: "",
    isClosable: 1,
    isShow: 0,
    children: [],
  },
]);
let froPermissionSearch = reactive({
  permissionName: "",
  status: -1,
});
const buttonRef = ref()
const tooltipRef = ref()
let dialogIsAdd = ref<boolean>(true);
let dialogFormVisible = ref<boolean>(false);
let froPermission = reactive<froPermission>({
  permissionId: null,
  permissionKey: "",
  permissionName: "",
  parentId: 0,
  createTime: "",
  createBy: "",
  path: "",
  component: "",
  permissionType: 0,
  status: 0,
  remark: "",
  icon: "",
  url: "",
  isClosable: 1,
  isShow: 0,
});
const ruleFormRef = ref<FormInstance>();
let searchFormRef = ref<FormInstance>();
let rules = reactive<FormRules<froPermission>>({
  permissionKey: [{required: true, message: "请输入权限标识", trigger: "blur"}],
  permissionName: [{required: true, message: "请输入权限名称", trigger: "blur"}],
  parentId: [{required: true, message: "请输入权限名称", trigger: "blur"}],
  path: [{required: true, message: "请输入权限名称", trigger: "blur"}],
  permissionType: [{required: true, message: "请输入权限名称", trigger: "blur"}],
});

function resetSearch(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.resetFields();
}

function getFroPermissionList() {
  return reqGetFroPermissionTreeList(froPermissionSearch).then((res) => {
    froPermissionList.value = res.data;
  });
}

/**
 * 重置表单
 * @param formEl
 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

function modifyFroPermission(node: froPermissionTreeVO) {
  // 排除children属性（如果直接赋值会导致children新增在目标froPermission身上，导致失去响应式)
  const {children: ignored, ...reset} = node;
  Object.assign(froPermission, reset);
  dialogIsAdd.value = false;
  dialogFormVisible.value = true;
}

function addFroPermission(parentId: number) {
  froPermission.parentId = parentId;
  dialogIsAdd.value = true; //表示新增dialog
  dialogFormVisible.value = true; //开启diaglog
}

let saveFroPermission = async (formEl: FormInstance | undefined) => {
  if (!formEl) return; //表单校验
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (dialogIsAdd.value) {
        reqAddFroPermission(froPermission).then(() => {
          ElMessage({
            message: "新增成功！",
            type: "success",
          });
        });
      } else {
        reqModifyFroPermission(froPermission).then(() => {
          ElMessage({
            message: "修改成功！",
            type: "success",
          });
        });
      }
      getFroPermissionList().finally(() => {
        // 刷新
        dialogFormVisible.value = false;
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const dateFormat = (row, column, cellValue) => {
  return moment(cellValue).format('YYYY-MM-DD HH:mm:ss');
};

function deleteFroPermission(permissionId: string | number) {
  ElMessageBox.confirm("删除之后无法恢复，请确认是否删除？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(() => {
        reqDeletefroPermission(permissionId).then(() => {
          ElMessage({
            message: "删除成功！",
            type: "success",
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除！",
        });
      });
}

onMounted(() => {
  getFroPermissionList();
});

const defaultProps = {
  children: "children",
  label: "permissionName",
};
watch(dialogFormVisible, () => {
  if (dialogFormVisible.value) {
    // 如果弹窗是打开状态，那么就发送请求
    reqGetFroPermissionFolder().then((res) => {
      froPermissionFlode.value[0].children = res.data;
    });
  }
});
</script>
<style lang="scss"></style>
<style>
.singleton-tooltip {
  transition: transform 0.3s var(--el-transition-function-fast-bezier);
}
</style>

